#include "stdafx.h"
#include "fuTreeListCtrl.h"
#include "wx/treelistctrl/treelistctrl.cpp.inl"

fuTreeListCtrl::fuTreeListCtrl(wxWindow *parent, 
                               wxWindowID id /*= -1*/, 
                               const wxPoint& pos /*= wxDefaultPosition*/, 
                               const wxSize& size /*= wxDefaultSize*/,
                               long style /*= wxTR_DEFAULT_STYLE*/, 
                               const wxValidator &validator /*= wxDefaultValidator*/,
                               const wxString& name /*= wxTreeListCtrlNameStr */) :
wxTreeListCtrl(parent,id,pos,size,style,validator,name),
m_minSize(0)
{
    Connect( wxEVT_PAINT, wxPaintEventHandler( fuTreeListCtrl::OnTreeListPaint ), NULL, this );
}

fuTreeListCtrl::~fuTreeListCtrl(void)
{
    Disconnect( wxEVT_PAINT, wxPaintEventHandler( fuTreeListCtrl::OnTreeListPaint ), NULL, this );
}

void fuTreeListCtrl::OnTreeListPaint(wxPaintEvent& event)
{
    event.Skip();
}

void fuTreeListCtrl::OnIdleResize( wxIdleEvent& )
{
    Update();
    if( GetRootItem().IsOk() ){
        for(int cnt = 0; cnt < GetColumnCount(); cnt++){
            int width_c = m_main_win->GetBestColumnWidth(cnt);
            int width_h = GetBestHeaderWidth(cnt);
            int width   = std::max(m_minSize,std::max(width_c,width_h));
            m_header_win->SetColumnWidth(cnt,width);
        }
        m_header_win->Refresh();
    }
    //Refresh();
    Disconnect(wxEVT_IDLE, wxIdleEventHandler( fuTreeListCtrl::OnIdleResize ), NULL, this);
}

void fuTreeListCtrl::ExpandAll(void)
{
    wxTreeItemId root = wxTreeListCtrl::GetRootItem();
    wxTreeListCtrl::ExpandAll(root);
}

void fuTreeListCtrl::ExpandAll(wxTreeItemId item)
{
    wxTreeListCtrl::ExpandAll(item);
}

void fuTreeListCtrl::ResizeColumns(int min_width)
{
    m_minSize = min_width;
    Connect( wxEVT_IDLE, wxIdleEventHandler( fuTreeListCtrl::OnIdleResize ), NULL, this );
}

long fuTreeListCtrl::GetBestHeaderWidth(long column)
{
    // determine header width
    int w = 0, h = 0;
    wxFont font = GetItemFont(GetRootItem());
    GetTextExtent(GetColumnText(column), &w, &h, NULL, NULL, font.Ok()? &font: NULL);
    w += 2*(MARGIN+3);
    return w;
}

wxTreeItemId 
fuTreeListCtrl::FindChild(wxTreeItemId parent,wxString name)
{
    wxTreeItemIdValue cookie;
    wxTreeItemId next = GetFirstChild(parent,cookie);
    while(next.IsOk() && name != GetItemText(next)){
        next = GetNextChild(parent,cookie);
    }

    return next;
}

size_t fuTreeListCtrl::GetSelectedCount(void) const
{
    wxArrayTreeItemIds ids;
    return GetSelections(ids);
}
